package mobileann.mafamily.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import com.mofind.android.base.L;

public class FormatConversionUtils {
	private static FormatConversionUtils _instance;

	public synchronized static FormatConversionUtils getInstance() {
		if (_instance == null) {
			_instance = new FormatConversionUtils();
		}
		return _instance;
	}

	/**
	 * Json 转成 List<Map<>>
	 * 
	 * @param jsonStr
	 * @return
	 */
	public List<Map<String, Object>> Json2List(String jsonStr) {
		List<Map<String, Object>> list = null;
		try {
			JSONArray jsonArray = new JSONArray(jsonStr);
			JSONObject jsonObj;
			list = new ArrayList<Map<String, Object>>();
			for (int i = 0; i < jsonArray.length(); i++) {
				jsonObj = (JSONObject) jsonArray.get(i);
				list.add(Json2Map(jsonObj.toString()));
			}
		} catch (Exception e) {
			L.e("maf", "error--", e);
		}
		return list;
	}

	/**
	 * Json 转成 Map<>
	 * 
	 * @param jsonStr
	 * @return
	 */
	public Map<String, Object> Json2Map(String jsonStr) {
		JSONObject jsonObject;
		try {
			jsonObject = new JSONObject(jsonStr);
			Iterator<String> keyIter = jsonObject.keys();
			String key;
			Object value;
			Map<String, Object> valueMap = new HashMap<String, Object>();
			while (keyIter.hasNext()) {
				key = keyIter.next();
				value = jsonObject.get(key);
				valueMap.put(key, value);
			}
			return valueMap;
		} catch (Exception e) {
			// TODO: handle exception
			L.e("maf", "error--", e);
		}
		return null;
	}
}
